// 二次封装axios 拦截器
import axios from 'axios'
import config from '@/config/index'
import { ElMessage } from 'element-plus'

const service = axios.create()

// 添加请求拦截器
service.interceptors.request.use(function (config) {
  // 在发送请求之前做些什么
  return config;
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error);
});

// 添加响应拦截器
service.interceptors.response.use(
  (res)=>{
    const {code, data, msg} = res.data
    if(code === 200){
      return data
    }else{
      const network_error = '网络错误'
      ElMessage.error(msg || network_error)
      return Promise.reject(msg || network_error)
    }
  }
);

function request(options){
  options.method = options.method || 'get';
  if(options.method.toLowerCase() === 'get'){
    options.params = options.data;
  }
  let isMock = config.mock;
  if(typeof isMock !== 'undefined'){
      isMock = options.mock;
  }

  if(config.env === 'prod'){
    service.defaults.baseURL = config.baseApi;
  }else{
    service.defaults.baseURL = isMock ? config.mockApi : config.baseApi;
  }

  return service(options)
}
export default request;